package com.online.fund.util;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * @description：httpClient工具类
 * @author：     hsy
 * @dateTime：   2017/1/5 15:22
 */
public class HttpClientUtil {
    private static PoolingHttpClientConnectionManager cm;
    private static IdleConnectionMonitorThread idleThread;
    private static String EMPTY_STR = "";
    private static String UTF_8 = "UTF-8";

    private static void init() {
        if (cm == null) {
        	synchronized(HttpClientUtil.class) {
        		if (cm == null) {
        			cm = new PoolingHttpClientConnectionManager();
                    cm.setMaxTotal(200);// 整个连接池最大连接数  
                    cm.setDefaultMaxPerRoute(20);// 每路由最大连接数，默认值是2  
                    idleThread = new IdleConnectionMonitorThread(cm);
                    idleThread.start();
        		}
        	}
        }
    }

    /**
     * 通过连接池获取HttpClient 
     *
     * @return
     */
    private static CloseableHttpClient getHttpClient() {
        init();
        return HttpClients.custom().setConnectionManager(cm).build();
    }

    /**
     *
     * @param url
     * @return
     */
    public static String httpGetRequest(String url) throws IOException {
        HttpGet httpGet = new HttpGet(url);
        return getResult(httpGet);
    }
    
    /**
     * 
     * 方法用途: 增加超时时间<br>
     * 实现步骤: <br>
     * @param url
     * @param timeout
     * @return
     * @throws IOException
     */
	public static String httpGetRequest(String url, int timeout) throws IOException {
		HttpGet httpGet = new HttpGet(url);
		httpGet.setConfig(RequestConfig.custom().setSocketTimeout(timeout * 1000).setConnectTimeout(timeout * 1000).build());
		return getResult(httpGet);
	}

    public static String httpGetRequest(String url, Map<String, Object> params) throws URISyntaxException, IOException {
        URIBuilder ub = new URIBuilder();
        ub.setPath(url);

        ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
        ub.setParameters(pairs);

        HttpGet httpGet = new HttpGet(ub.build());
        return getResult(httpGet);
    }
    
    public static String httpGetRequest(String url, int timeout, Map<String, Object> params) throws URISyntaxException, IOException {
        URIBuilder ub = new URIBuilder();
        ub.setPath(url);

        ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
        ub.setParameters(pairs);

        HttpGet httpGet = new HttpGet(ub.build());
        httpGet.setConfig(RequestConfig.custom().setSocketTimeout(timeout * 1000).setConnectTimeout(timeout * 1000).build());
        return getResult(httpGet);
    }

    public static String httpGetRequest(String url, Map<String, Object> headers, Map<String, Object> params)
            throws URISyntaxException, IOException {
        URIBuilder ub = new URIBuilder();
        ub.setPath(url);

        ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
        ub.setParameters(pairs);

        HttpGet httpGet = new HttpGet(ub.build());
        for (Map.Entry<String, Object> param : headers.entrySet()) {
            httpGet.addHeader(param.getKey(), String.valueOf(param.getValue()));
        }
        return getResult(httpGet);
    }
    
    public static String httpGetRequest(String url, int timeout, Map<String, Object> headers, Map<String, Object> params)
            throws URISyntaxException, IOException {
        URIBuilder ub = new URIBuilder();
        ub.setPath(url);

        ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
        ub.setParameters(pairs);

        HttpGet httpGet = new HttpGet(ub.build());
        httpGet.setConfig(RequestConfig.custom().setSocketTimeout(timeout * 1000).setConnectTimeout(timeout * 1000).build());
        for (Map.Entry<String, Object> param : headers.entrySet()) {
            httpGet.addHeader(param.getKey(), String.valueOf(param.getValue()));
        }
        return getResult(httpGet);
    }

    public static String httpPostRequest(String url) throws IOException {
        HttpPost httpPost = new HttpPost(url);
        return getResult(httpPost);
    }

    public static String httpPostRequest(String url,int timeout, Map<String, Object> params) throws IOException {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(RequestConfig.custom()
                .setSocketTimeout(timeout * 1000)
                .setConnectTimeout(timeout * 1000)
                .build());
        ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
        httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));
        return getResult(httpPost);
    }

    public static String httpPostRequest(String url, Map<String, Object> headers, Map<String, Object> params)
            throws IOException {
        HttpPost httpPost = new HttpPost(url);

        for (Map.Entry<String, Object> param : headers.entrySet()) {
            httpPost.addHeader(param.getKey(), String.valueOf(param.getValue()));
        }

        ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
        httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));

        return getResult(httpPost);
    }

    private static ArrayList<NameValuePair> covertParams2NVPS(Map<String, Object> params) {
        ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
        for (Map.Entry<String, Object> param : params.entrySet()) {
            pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(param.getValue())));
        }

        return pairs;
    }

    /**
     * 处理Http请求 
     *
     * @param request
     * @return
     */
    private static String getResult(HttpRequestBase request) throws IOException {
        // CloseableHttpClient httpClient = HttpClients.createDefault();  
        CloseableHttpClient httpClient = getHttpClient();
        CloseableHttpResponse response = httpClient.execute(request);
        // response.getStatusLine().getStatusCode();
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            // long len = entity.getContentLength();// -1 表示长度未知
            String result = EntityUtils.toString(entity, UTF_8);
            response.close();
            // httpClient.close();
            return result;
        }
        return EMPTY_STR;
    }
    
    /**
     * 
     * 方法用途: 关闭线程，关闭连接池<br>
     * 实现步骤: <br>
     */
    public static void closeConnectionPool() {
    	if (idleThread != null && idleThread.isAlive()) {
    		idleThread.shutdown();
    	}
    	
    	if (cm != null) {
    		cm.close();
    	}
    }

    /**
     * 
     * <p>Description: 关闭长时间不再使用的连接</p>
     * @date 2018年1月23日
     * @author 张飞 
     * @version 1.0
     * <p>Company:Mopon</p>
     * <p>Copyright:Copyright(c)2017</p>
     */
    public static class IdleConnectionMonitorThread extends Thread {  
    	  
        private final HttpClientConnectionManager connMgr;  
        private volatile boolean shutdown;  
      
        public IdleConnectionMonitorThread(HttpClientConnectionManager connMgr) {  
            super();  
            this.connMgr = connMgr;  
        }  
      
        @Override  
        public void run() {  
            try {  
                while (!shutdown) {  
                    synchronized (this) {  
                        wait(5000);  
                        // 关闭失效的连接  
                        connMgr.closeExpiredConnections();  
                        // 可选的, 关闭30秒内不活动的连接  
                        connMgr.closeIdleConnections(30, TimeUnit.SECONDS);  
                    }  
                }  
            } catch (InterruptedException ex) {  
                // terminate  
            }  
        }  
      
        public void shutdown() {  
            shutdown = true;  
            synchronized (this) {  
                notifyAll();  
            }  
        }  
    }
}  
